from django.shortcuts import render, HttpResponse, redirect
from web import models
from web.utils.pagination import Pagination

from web.utils.form import UserModelForm, PrettyModelForm, PrettyEditModelForm


def user_list(request):
    """用户列表"""
    # 去数据库获取所有的用户信息
    queryset = models.UserInfo.objects.all()
    page_object = Pagination(request, queryset, page_size=10)
    context = {
        'queryset': page_object.page_queryset,
        'page_string': page_object.html(),
    }
    # 通过模板语法，将queryset传到前端
    return render(request, 'user_list.html', context)


def user_add(request):
    """添加用户"""
    if request.method == "GET":
        context = {
            'gender_choices': models.UserInfo.gender_choices,
            'depart_list': models.Department.objects.all()
        }
        return render(request, 'user_add.html', context)
    # 如果是post请求，获取用户提交的数据
    user = request.POST.get('user')
    pwd = request.POST.get('pwd')
    age = request.POST.get('age')
    account = request.POST.get('ac')
    ctime = request.POST.get('ctime')
    gender = request.POST.get('gd')
    depart_id = request.POST.get('dp')
    # 添加到数据库中
    models.UserInfo.objects.create(name=user, password=pwd, age=age, account=account, create_time=ctime, gender=gender,
                                   depart_id=depart_id)
    # 返回到用户列表页面
    return redirect('/user/list/')


def user_model_form_add(request):
    """添加用户 ModelForm实现"""
    if request.method == "GET":
        form = UserModelForm()
        return render(request, 'user_model_form_add.html', {'form': form})
    # 用户通过post提交数据，数据校验
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        # 如果数据合法，保存到数据库
        form.save()
        return redirect("/user/list/")
        # print(form.cleaned_data)
    # else:
    #     print(form.errors)
    # 校验失败，在页面显示错误信息
    return render(request, 'user_model_form_add.html', {'form': form})


def user_edit(request, nid):
    """编辑用户"""
    # 根据ID去数据库获取要编辑的那一行数据
    row_object = models.UserInfo.objects.filter(id=nid).first()
    if request.method == "GET":
        form = UserModelForm(instance=row_object)
        return render(request, 'user_edit.html', {'form': form})

    form = UserModelForm(data=request.POST, instance=row_object)  # 通过instance=row_object 实现修改，没有这个参数，只能实现新增数据
    if form.is_valid():
        form.save()
        return redirect('/user/list/')
    return render(request, 'user_edit.html', {'form': form})


def user_delete(request, nid):
    """删除用户"""
    models.UserInfo.objects.filter(id=nid).delete()
    return redirect('/user/list/')
